//
//  CCQCountDownButton.swift
//  Fangxukanghan
//
//  Created by 常超群的MacBookPro on 2021/4/19.
//

import UIKit
/// 显示倒计时的按钮
public class CCQCountDownButton: UIButton {
    
    private var timer: Timer?
    private var totalSeconds: Int = 0
    public var onFinishClosure: CCQVoidClosure?
    
    public func countDownTaskWith(seconds: Int, _ onFinishClosure: CCQVoidClosure? = nil) {
        guard timer == nil else { return }
        totalSeconds = seconds
        self.onFinishClosure = onFinishClosure
        
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { timer in
            if self.totalSeconds <= 0 {
                self.timerOnfinish()
            } else {
                self.onTick()
            }
        })
        timer?.fire()
    }
    
    private func onTick() {
        
        let hours = Int(totalSeconds / 3600)
        let minutes = Int((totalSeconds - 3600 * hours) / 60)
        let seconds = totalSeconds % 60
        var timeLeftDesc = ""
        if hours > 0 {
            timeLeftDesc = String(format: "%.2d:%.2d:%.2d", hours, minutes, seconds)
        } else if minutes > 0 {
            timeLeftDesc = String(format: "%.2d:%.2d", minutes, seconds)
        } else {
            timeLeftDesc = String(format: "%.2ds", seconds)
        }
        //设置按钮显示读秒效果
        DispatchQueue.main.async {
            self.setTitle(timeLeftDesc, for: .normal)
            self.isEnabled = false
        }
        
        totalSeconds -= 1
    }
    
    private func timerOnfinish() { // 倒计时结束，关闭
        isEnabled = true
        onFinishClosure?()
        cancelCountDown()
    }
    
    public func cancelCountDown() {
        timer?.invalidate()
        timer = nil
        totalSeconds = 0
        onFinishClosure = nil
    }

}
